const deepProxy = (obj, handler) => {

    const createProxy = (target) => {

        /* 如果被代理的对象是引用数据类型: 真身进去 代理出来 */
        if (typeof target === 'object' && target !== null) {
            for (let key in target) {
                const value = target[key]

                // 对每个key-value 都递归代理
                target[key] = createProxy(value);
            }

            // target真身进去 proxy代理出来
            return new Proxy(target, handler);
        }

        // 如果是基本数据类型 真身进去 真身出来
        return target;
    };





    return createProxy(obj);
};

const data = {
    name: 'John',
    age: 30,
    hobbies: ['reading', 'writing'],
    dog: {
        nickname: "臭皮",
        legs: 4,
    }
};

const dataProxy = deepProxy(
    // 被代理的对象
    data,

    // 被代理对象的【操作器】
    {
        get: function (target, key, receiver) {
            console.log("getter", key);
            // console.log('getter:target, key, receiver=', target, key, receiver);

            // return target[key]
            // return receiver.get(key)
            return Reflect.get(target, key, receiver);
        },

        set: function (target, key, value, receiver) {
            console.log("setter", key);
            // console.log('setter:target, key, value, receiver=', target, key, value, receiver);

            // return (target[key] = value)
            return Reflect.set(target, key, value, receiver);
        },

        deleteProperty: function (target, prop) {
            console.log("deleter", prop);
            // delete target[prop];
            return Reflect.deleteProperty(target, prop);
        },
    }

);

/* 通过代理读取原始数据 */
// console.log(dataProxy.name); // 读取属性: name
// console.log(dataProxy.hobbies[0]); // 读取属性: hobbies
// console.log(dataProxy.dog.nickname); // 读取属性: dog, 读取属性: nickname

/* 新增与修改 */
// dataProxy.age = 35; // 设置属性: age = 35
// dataProxy.hobbies.push('coding'); // 设置属性: hobbies = ['reading', 'writing', 'coding']
// dataProxy.dog.nickname = '可爱'; // 设置属性: dog, 设置属性: nickname = '可爱'

/* 删除 */
// delete dataProxy.age
// delete dataProxy.hobbies[1]

/* 数组操作 */
// dataProxy.hobbies.pop()
// dataProxy.hobbies.unshift("running")
// dataProxy.hobbies.splice(1,0,"talking")

// 打印原始数据
// console.log(data);